Validate Binary Search Tree
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
*- The right subtree of a node contains only nodes with keys greater than the node's key.
*- Both the left and right subtrees must also be binary search trees.
题目大意:判断给定的树是不是二叉搜索树
题目难度:Medium
import java.util.Stack;
/**
* Created by gzdaijie on 16/6/5
* 对于二叉搜索树,中序遍历的结果是递增的
*/
public class Solution {
public boolean isValidBST(TreeNode root) {
long pre = Integer.MIN_VALUE;
Stack<TreeNode> stack = new Stack<>();
pre = pre - 1;
while (true) {
while (root != null) {
stack.push(root);
root = root.left;
}
if (stack.isEmpty()) break;
TreeNode tmp = stack.pop();
if (tmp.val <= pre) return false;
if (tmp.right != null) root = tmp.right;
pre = tmp.val;
}
return true;
}
}